package com.app.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtil {

	/**
	 * 文件夹压缩方法
	 * @param path 输入要压缩的文件夹的路径 
	 * @return 返回压缩好的文件的路径
	 */
    public static String outZip(String targetPath) {
        File file = new File(targetPath);
        String zipFileName = targetPath.substring(0, targetPath.lastIndexOf("\\")+1) + file.getName()+".zip";
        File zipFile = new File(zipFileName);
        InputStream input = null;
        ZipOutputStream zipOut = null;
        try{
        	 zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
             // zip的名称为
             zipOut.setComment(file.getName());
             if (file.isDirectory()) {
                 File[] files = file.listFiles();
                 for (int i = 0; i < files.length; ++i) {
                     input = new FileInputStream(files[i]);
                     zipOut.putNextEntry(new ZipEntry(file.getName() + File.separator + files[i].getName()));
                     int temp = 0;
                     while ((temp = input.read()) != -1) {
                         zipOut.write(temp);
                     }
                     input.close();
                     if(files[i].exists()) {
     					files[i].delete();
     				}
                 }
             }
        }catch(Exception e){
        	e.printStackTrace();
        }finally{
        	try {
				zipOut.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
        return zipFileName;
    }
}
